package com.zc.hadoop.mapreduce2;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 * 标准的MapReduce 构建方式
 *
 */
public class StandardMapReduce extends Configured implements Tool {

	/**
	 * Mapper
	 */
	public static class StandardMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		// 定义map输出key、value值
		protected Text mapOutputKey = new Text();
		// 以1开始计数
		protected IntWritable mapOutputVlaue = new IntWritable(1);

		@Override
		protected void cleanup(Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			// TODO Auto-generated method stub
			super.cleanup(context);
		}

		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {

			// 获取每行数据
			String lineValue = value.toString();

			System.out.println("Mapper lineValue=" + lineValue);

			// 切割数据
			StringTokenizer st = new StringTokenizer(lineValue);

			while (st.hasMoreTokens()) {
				// 获取下一个值
				String wordValue = st.nextToken();

				System.out.println("Mapper wordValue=" + wordValue);

				mapOutputKey.set(wordValue);
				context.write(mapOutputKey, mapOutputVlaue);

			}

			super.map(key, value, context);
		}

		@Override
		protected void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			// TODO Auto-generated method stub
			super.setup(context);
		}

	}

	/**
	 * Reduce
	 */
	public static class StandardReduce extends Reducer<Text, IntWritable, Text, IntWritable> {

		// 定义输出值
		protected IntWritable outputValue = new IntWritable();

		@Override
		protected void cleanup(Reducer<Text, IntWritable, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			// TODO Auto-generated method stub
			super.cleanup(context);
		}

		@Override
		protected void reduce(Text key, Iterable<IntWritable> values,
				Reducer<Text, IntWritable, Text, IntWritable>.Context content)
				throws IOException, InterruptedException {

			int sum = 0;

			for (IntWritable value : values) {
				System.out.println("Reducer values value=" + value);
				sum += value.get();
			}

			System.out.println("Reducer sum=" + sum);

			outputValue.set(sum);
			content.write(key, outputValue);

			super.reduce(key, values, content);
		}

		@Override
		protected void setup(Reducer<Text, IntWritable, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			// TODO Auto-generated method stub
			super.setup(context);
		}

	}

	@Override
	public int run(String[] args) throws Exception {

		Configuration config = new Configuration();

		Job job = this.parseInputAndOutput(config, args, this);

		// 设置mapper
		job.setMapperClass(StandardMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);

		// 设置reduce
		job.setReducerClass(StandardReduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);

		//=====================shuffle=====================
//		job.setCombinerClass(StandardMapReduce.class);
//		job.setPartitionerClass(cls);
//		job.setGroupingComparatorClass(cls);
//		job.set...
		//=====================shuffle=====================
		
		// 提交job 等待运行结束 并在客户端显示运行信息
		boolean flag = job.waitForCompletion(true);
		return flag ? 0 : 1;
	}

	public Job parseInputAndOutput(Configuration conf, String[] args, Tool tool) throws IOException {
		// 设置job
		Job job = Job.getInstance(conf, tool.getClass().getSimpleName());

		// 设置job运行类
		job.setJarByClass(this.getClass());

		// 数据的输入
		Path inputDir = new Path(args[0]);
		FileInputFormat.addInputPath(job, inputDir);

		// 设置输出
		Path outputDir = new Path(args[1]);
		FileOutputFormat.setOutputPath(job, outputDir);
		
		return job;
	}
	
	
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		int status = ToolRunner.run(conf, new StandardMapReduce(), args);
		
		// System.exit(0)是将你的整个虚拟机里的内容都停掉了 ，而dispose()只是关闭这个窗口，但是并没有停止整个application exit() 。无论如何，内存都释放了！也就是说连JVM都关闭了，内存里根本不可能还有什么东西
		// System.exit(0)是正常退出程序，而System.exit(1)或者说非0表示非正常退出程序
		// System.exit(status)不管status为何值都会退出程序。和return 相比有以下不同点：   return是回到上一层，而System.exit(status)是回到最上层
		System.exit(status);
	}
	

}
